/**
 * @author cqb 2016-04-27.
 * @module RadioGroup
 */

import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import Radio from '../Input/Radio';
import FormItem from '../FormItem';
import './RadioGroup.less';

/**
 * RadioGroup 类
 * @class RadioGroup
 * @constructor
 * @extend BaseComponent
 */
class RadioGroup extends React.PureComponent {
    static displayName = 'RadioGroup';
    
    static defaultProps = {
        value: '',
        layout: 'inline',
        valueField: 'id',
        textField: 'text'
    };

    itemMap = {};

    state = {
        value: `${this.props.value}`
    }

    /**
     * 重构数据格式
     * @param data
     * @private
     */
    buildData (data) {
        if (!data) {
            return null;
        }
        if (Object.prototype.toString.apply(data) === '[object Array]') {
            const one = data[0];
            if (Object.prototype.toString.apply(one) === '[object String]') {
                return data.map((item, index) => {
                    const option = {id: `${index}`, text: item};
                    return option;
                });
            }
            if (Object.prototype.toString.apply(one) === '[object Object]') {
                return data;
            }
            return null;
        }

        if (Object.prototype.toString.apply(data) === '[object Object]') {
            const ret = [];
            for (const id in data) {
                const item = {id, text: data[id]};
                ret.push(item);
            }
            return ret;
        }

        return null;
    }

    /**
     * 记录当前的checkbox对象
     * @param {[type]} ref [description]
     */
    addCheckBox = (value, ref) => {
        if (ref) {
            this.itemMap[value] = ref;
        }
    }

    /**
     * 子元素移除后回调， 删除记录的对象
     * @param  {[type]} item [description]
     * @return {[type]}      [description]
     */
    unbind = (value) => {
        delete this.itemMap[value];
    }

    /**
     * 值变化回调
     * @method handleChange
     * @param value {String} 当前操作对象的值
     * @param checked   {Boolean} 知否选中
     * @param event     {Event} 事件对象
     * @param item  {Object} 当前操作对象
     */
    onChange = (v) => {
        if (this.props.disabled) {
            return;
        }


        this.setState({
            value: v
        }, () => {
            if (this.props.onChange) {
                this.props.onChange(v);
            }
        });
    }

    /**
     * 渲染子节点
     * @method _renderItems
     * @returns {Array} 子对象
     * @private
     */
    renderItems () {
        let {valueField, textField, name, data} = this.props;
        data = this.buildData(data);
        data = data || [];
        const currentValue = `${this.state.value}`;
        
        name = name || `radio_${new Date().getTime()}`;
        return data.map(function (item, index) {
            const value = `${item[valueField]}`;
            const text = item[textField];
            const checked = currentValue === value;
            return (
                <Radio
                    key={index}
                    disabled={item._disabled || this.props.disabled}
                    ref={this.addCheckBox.bind(this, value)}
                    unbind={this.unbind.bind(this, value)}
                    type='radio'
                    value={value}
                    label={text}
                    checked={checked}
                    name={name}
                    onChange={this.onChange}
                />);
        }, this);
    }

    setValue (value) {
        this.setState({value});
    }

    render () {
        let {className, layout, size} = this.props;
        className = classNames(
            className,
            'cm-radio-group',
            {
                'cm-radio-group-stack': layout === 'stack',
                'cm-radio-group-stick': this.props.stick,
                [`cm-radio-group-${size}`]: size
            }
        );

        return (
            <span className={className} style={this.props.style}>
                {this.renderItems()}
            </span>
        );
    }
}

RadioGroup.propTypes = {
    /**
     * 数据源
     * @attribute data
     * @type {Array}
     */
    data: PropTypes.any,
    /**
     * 默认值
     * @attribute value
     * @type {String}
     */
    value: PropTypes.any,
    /**
     * 只读属性
     * @attribute readOnly
     * @type {Boolean}
     */
    readOnly: PropTypes.bool,
    /**
     * 禁用属性
     * @attribute disabled
     * @type {Boolean}
     */
    disabled: PropTypes.bool,
    /**
     * 组名
     * @attribute name
     * @type {String}
     */
    name: PropTypes.string,
    /**
     * class样式名称
     * @attribute className
     * @type {String}
     */
    className: PropTypes.string,
    /**
     * 行式inline、堆积stack布局
     * @attribute layout
     * @type {String}
     */
    layout: PropTypes.oneOf(['inline', 'stack']),
    /**
     * value字段
     * @attribute valueField
     * @type {String}
     */
    valueField: PropTypes.string,
    /**
     * 显示字段
     * @attribute textField
     * @type {String}
     */
    textField: PropTypes.string,
    /**
     * 值变化回调
     * @attribute onChange
     * @type {Function}
     */
    onChange: PropTypes.func
};

FormItem.register(RadioGroup, 'radio2', 'array');

export default RadioGroup;
